<template>
  <div class="card-container">
    <el-breadcrumb
      class="breadcrumb-margin"
      separator-class="el-icon-arrow-right"
    >
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card full-card">
      <div slot="header" class="header-container">
        <el-row :gutter="30" class="card-row">
          <el-col :span="8">
            <el-input
              placeholder="请输入名字(空值默认查询所有用户)"
              v-model="selectName"
              clearable
              class="input-with-select"
              @keyup.enter.native="selectUser({name:selectName,page: 1,pageSize: 10})"
              @clear="selectUser({name:null,page: 1,pageSize: 10})"
            >
              <template slot="append">
                <el-button
                  icon="el-icon-search"
                  @click="selectUser({name:selectName,page: 1,pageSize: 10})"
                ></el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="success" @click="dialogFormVisible = true"
              >添加用户</el-button
            >
          </el-col>
          <el-col :span="4">
            <el-button type="danger" @click="deleteUsers(multipleSelection)"
              >批量删除用户</el-button
            >
          </el-col>
        </el-row>
      </div>

      <el-table
        :data="userList"
        border
        style="width: 100%"
        class="hospital-table"
         @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type=index label="#" width="70"> </el-table-column>
        <el-table-column prop="name" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="100">
        </el-table-column>
        <el-table-column prop="avatar" label="头像" width="150">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" class="avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="password" label="密码" width="150">
        </el-table-column>
        <el-table-column prop="phone" label="电话号" width="150">
        </el-table-column>
        <el-table-column prop="idNumber" label="身份证号" width="200">
        </el-table-column>

        <el-table-column prop="roleName" label="角色类型" width="100">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200">
        </el-table-column>
        <el-table-column prop="createUser" label="创建人" width="80">
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="200">
        </el-table-column>
        <el-table-column prop="updateUser" label="修改人" width="80">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="updateStatus(scope.row.status, scope.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="slot">
            <el-tooltip
              effect="dark"
              content="修改"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="selectUserById(slot.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
              
            >
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteUsers([slot.row.id])"></el-button>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="设置权限"
              placement="top"
              :enterable="false"
            >
              <el-button type="info" icon="el-icon-setting" circle></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSelect.pageSize"
          layout="prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="所添加用户信息"
      :visible.sync="dialogFormVisible"
      width="50%"
      :before-close="handleClose"
      custom-class="hospital-dialog"
    >
      <el-form
        :model="userForm"
        :rules="rules"
        ref="userForm"
        label-width="120px"
        class="userForm hospital-form"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="身份证号"
          prop="idNumber"
          placeholder="请输入身份证号"
        >
          <el-input v-model="userForm.idNumber"></el-input>
        </el-form-item>
        <el-form-item label="电话号" prop="phone" placeholder="请输入电话号">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" placeholder="请输入密码">
          <el-input v-model="userForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色类型">
            <el-option label="管理员" :value="1"></el-option>
            <el-option label="医生" :value="2"></el-option>
            <el-option label="普通用户" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadRequest"
          >
            <div class="avatar-container">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer hospital-dialog-footer">
        <el-button @click="dialogFormVisible = false" class="cancel-button"
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm(userForm)"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="当前用户信息"
      :visible.sync="dialogUpdateFormVisible"
      width="50%"
      :before-close="handleClose"
      custom-class="hospital-dialog"
    >
      <el-form
        :model="user"
        :rules="rules"
        ref="user"
        label-width="120px"
        class="userForm hospital-form"
      >
        <!-- 用户ID，通常为不可编辑字段，隐藏或禁用 -->
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="user.id" disabled></el-input>
        </el-form-item>

        <!-- 姓名 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name"></el-input>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="user.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 身份证号 -->
        <el-form-item
          label="身份证号"
          prop="idNumber"
          placeholder="请输入身份证号"
        >
          <el-input v-model="user.idNumber"></el-input>
        </el-form-item>

        <!-- 电话号 -->
        <el-form-item label="电话号" prop="phone" placeholder="请输入电话号">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>

       

        <!-- 密码 -->
        <el-form-item label="密码" prop="password" placeholder="请输入密码">
          <el-input v-model="user.password" type="password"></el-input>
        </el-form-item>

        <!-- 用户状态 -->
        <el-form-item label="用户状态" prop="status">
          <el-switch
            v-model="user.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>

        <!-- 角色类型 -->
        <el-form-item label="角色类型" prop="roleId">
          <el-select v-model="user.roleId" placeholder="请选择角色类型">
            <el-option label="管理员" :value="1"></el-option>
            <el-option label="医生" :value="2"></el-option>
            <el-option label="普通用户" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <!-- 用户头像 -->
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadRequest"
          >
            <div class="avatar-container">
              <img v-if="user.avatar" :src="user.avatar" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer hospital-dialog-footer">
        <el-button @click="dialogFormVisible = false" class="cancel-button"
          >取 消</el-button
        >
        <el-button type="primary" @click="updateUser()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
      

<script>
export default {
  name: "UserVue",
  data() {
    return {
      dialogFormVisible: false,
      dialogUpdateFormVisible: false,
      selectName: null,
      pageSelect: {
      name: null,
      page: 1,
      pageSize: 10,
      },
      multipleSelection: [], 
      currentPage: 1,
      userList: [],
      total: null,
      userForm: {
        name: "",
        idNumber: "",
        phone: "",
        roleId: null,
        status: null,
        id: "",
        password: "",
        gender: "",
      },
      user: {
        id: null,
        name: "",
        gender: "",
        avatar: "",
        password: "",
        phone: "",
        roleId: null,
        idNumber: "",
        status: null,
      },
      formLabelWidth: "120px",
      imageUrl: "",
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "姓名长度应在 2 到 20 个字符之间",
            trigger: "blur",
          },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        idNumber: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            pattern: /^[1-9]\d{5}(18|19|20)?\d{9}(\d|X)$/,
            message: "身份证号格式不正确",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入电话号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "电话号码格式不正确",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度应在 6 到 20 个字符之间",
            trigger: "blur",
          },
        ],
        status: [
          { required: true, message: "请选择用户状态", trigger: "change" },
        ],
        roleId: [
          { required: true, message: "请选择角色类型", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleStatusChange(row) {
      // 这里手动更新 status 的值
      row.status = row.status === 1 ? 0 : 1;
    },
    async selectUser(pageSelect) {
      const result = await this.$http.get("webPage/user/pageSelect", {
        params: {
         name: pageSelect.name,
         page: pageSelect.page,
         pageSize: pageSelect.pageSize    
        },
      });
      this.userList = result.data.data.records;
      this.total = result.data.data.total;
    },
    async selectUserById(id) {
      const response = await this.$http.get(`/webPage/user/${id}`);
      this.user = response.data.data;
      this.dialogUpdateFormVisible = true;
    },
    updateUser(){
       this.$http.put("/webPage/user/update", this.user)
    .then(() => {
      // 如果请求成功，查询用户并关闭弹出框
      this.selectUser({name:null,page:this.currentPage,pageSize:this.pageSelect.pageSize});  // 确保调用函数
      this.dialogUpdateFormVisible = false;
      this.$message.success("修改成功");
    })
    },
    deleteUsers(ids){
       this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete(`/webPage/user/delete?ids=${ids}`)
  .then( (response) => {
    if(response.data.code===1){
        this.$message.success("删除成功")
        this.selectUser({name:null,page:this.currentPage,pageSize:this.pageSelect.pageSize})
      }
       
      
    
  })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    async handleCurrentChange() {
      const result = await this.$http.get("webPage/user/pageSelect", {
        params: {
          name: this.pageSelect.name,
          page: this.currentPage,
          pageSize: this.pageSelect.pageSize,
        },
      });
      this.userList = result.data.data.records;
      this.total = result.data.data.total;
    },
    async updateStatus(afterStatus, id) {
      this.$http.post(`/webPage/user/status/${afterStatus}?id=${id}`);
    },
    handleAvatarSuccess(response) {
      // 上传成功的处理逻辑，例如更新图片 URL
      this.imageUrl = response.data.data; // 假设后端返回的图片 URL 在 response.data.data
    },
    beforeAvatarUpload(file) {
      // 上传前的处理逻辑，例如校验文件类型、大小等
      const isImage = file.type.startsWith("image/");
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isImage) {
        this.$message.error("上传的文件必须是图片!");
      }
      if (!isLt10M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }

      return isImage && isLt10M;
    },
    uploadRequest({ file }) {
      // 使用 axios 手动发起上传请求
      const formData = new FormData();
      formData.append("file", file); // 将文件添加到 formData 中

      this.$http
        .post("webPage/common/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          // 调用上传成功的回调
          this.handleAvatarSuccess(response);
        })
        .catch((error) => {
          this.$message.error("上传失败");
          console.error(error);
        });
    },
    submitForm(form) {
      this.$http.post("webPage/user/add", {
        name: form.name,
        phone: form.phone,
        gender: form.gender,
        status: form.status,
        roleId: form.roleId,
        avatar: this.imageUrl,
        idNumber: form.idNumber,
        password: form.password,
      });
      this.selectUser({name:null,page:1,pageSize:this.pageSelect.pageSize});
      this.dialogFormVisible = false;
      this.$message.success("添加成功");
    },
    handleSelectionChange(val) {
      // 将选中的项的 id 存入 multipleSelection
      this.multipleSelection = val.map(item => item.id);
    }
  },
  async created() {
    this.selectUser({name:null,page:this.pageSelect.page,pageSize:this.pageSelect.pageSize})
    
  },
};
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

/* 添加 breadcrumb-margin 类并设置 margin-bottom */
.breadcrumb-margin {
  margin-bottom: 20px; /* 调整此值可以控制距离 */
}

/* 父容器 card-container 设为 flex 布局，确保卡片占满剩余空间 */
.card-container {
  .card-container {
    display: flex;
    flex-direction: column;
    padding: 10px;
    height: 100vh;
    background-color: #eef1f6; /* 使用浅色背景，符合医院风格 */
  }
}

/* 卡片整体占满剩余空间 */
.full-card {
  width: calc(100% - 30px); /* 减少右端30px的间距 */
  margin-top: 10px; /* 减少与面包屑的距离 */
  margin-right: 30px; /* 设置与右端的距离 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 调整阴影为轻量风格 */
  border-radius: 6px; /* 圆角效果 */
  padding: 15px; /* 调整卡片内边距 */
  background-color: #f9f9f9; /* 更加柔和的背景色，适合医院风格 */
}
.div

/* 表格样式美化，符合医院风格 */
.hospital-table {
  border: 1px solid #e0e0e0; /* 调整边框颜色 */
  border-radius: 6px; /* 表格边角圆滑 */
}

.hospital-table :deep(.el-table__header-wrapper) {
  background-color: #edf2fa; /* 更柔和的表头颜色 */
}

.hospital-table :deep(th) {
  text-align: center;
  background-color: #f0f4f8; /* 更柔和的表头颜色 */
  font-weight: bold;
  font-size: 14px;
  color: #3a7fda; /* 专业的蓝色 */
}

.hospital-table :deep(td) {
  padding: 12px 8px; /* 增加单元格间距 */
  text-align: center;
  font-size: 14px;
  color: #5a6b7c; /* 字体颜色微调，更加舒适 */
  border-bottom: 1px solid #ebebeb; /* 调整行间隔 */
}
.hospital-table :deep(.el-table__body tr:nth-child(odd)) {
  background-color: #f9f9f9; /* 浅色背景 */
}

.hospital-table :deep(.el-table__body tr:nth-child(even)) {
  background-color: #ffffff; /* 白色背景 */
}

.hospital-table :deep(.el-table__body tr:hover) {
  background-color: #c3e2fd !important; /* 更浅的浅蓝色背景 */
}
.hospital-table :deep(.el-table__body td:hover) {
  background-color: #7bc3f6 !important; /* 较深的浅蓝色背景 */
}
/* 解决鼠标切换行时悬浮效果不立即生效的问题 */
.hospital-table :deep(.el-table__row:hover td) {
  background-color: #c3e2fd !important; /* 确保鼠标悬停时整行生效 */
}
.hospital-table :deep(.el-table__row td:hover) {
  background-color: #7bc3f6 !important; /* 鼠标悬停在单元格上时单元格高亮 */
}

/* 操作列的按钮样式 */
.table-action-btn {
  color: #3b82f6; /* 医疗风格的蓝色 */
  font-weight: bold;
}

.header-container {
  height: 50px; /* 增加头部高度，给元素更多空间 */
  background-color: #f0f4f8; /* 更加柔和的背景色 */
  border-bottom: 1px solid #dcdfe6; /* 下边框，增加分隔感 */
  padding: 10px 15px; /* 添加内边距 */
}
.input-with-select {
  height: 40px; /* 调整输入框高度 */
  border-radius: 4px; /* 添加圆角 */
  border: 1px solid #dcdfe6; /* 边框颜色与整体风格统一 */
}

.card-row {
  height: 50px;
  display: flex;
  align-items: center;
}
/* 分页样式优化 */
.block {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-pagination {
  background-color: #f9fafc; /* 分页区域背景 */
  padding: 10px 15px; /* 分页内边距 */
  border-radius: 6px; /* 圆角效果 */
}

.el-pagination :deep(.el-pager li) {
  font-size: 14px;
  color: #3a7fda; /* 使用专业蓝色 */
  margin: 0 5px;
}

.el-pagination :deep(.el-pager li.active) {
  background-color: #3a7fda;
  color: #fff;
}

/* 表单项悬浮效果 */
.input-with-select:hover,
.el-select:hover,
.el-input:hover,
.el-input__inner:hover {
  background-color: #e3f2fd; /* 与表格行悬浮效果一致的背景色 */
  border-color: #3a7fda; /* 改变边框颜色，突出效果 */
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden; /* 圆形裁剪图片 */
  cursor: pointer;
  border: 2px solid #f0f0f0; /* 轻微的边框 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  transition: all 0.3s ease; /* 动画过渡效果 */
}

.avatar-uploader:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2); /* 鼠标悬停时增加阴影 */
  transform: scale(1.05); /* 悬停时轻微放大 */
}

.avatar-container {
  width: 100px; /* 可以根据需求调整 */
  height: 100px; /* 可以根据需求调整 */
  border-radius: 50%;
  overflow: hidden; /* 圆形裁剪图片 */
  border: 2px solid #f0f0f0; /* 轻微的边框 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  transition: all 0.3s ease; /* 动画过渡效果 */
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar-container:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2); /* 鼠标悬停时增加阴影 */
  transform: scale(1.05); /* 悬停时轻微放大 */
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 图片按比例裁剪，保持覆盖 */
  border-radius: 50%; /* 将图片本身也裁剪成圆形 */
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #f0f0f0; /* 默认背景色 */
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.avatar-uploader-icon:hover {
  background-color: #e6e6e6; /* 鼠标悬停时背景变浅 */
}

::v-deep .hospital-dialog {
  background-color: #c0d7f8; /* 柔和的背景色 */
  border-radius: 10px; /* 圆角边框 */
  padding: 15px; /* 内边距增加，保持空间感 */
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1); /* 轻量阴影 */
}

::v-deep .hospital-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 表单项之间增加间距 */
::v-deep .el-form-item {
  margin-bottom: 16px;
}

.el-input__inner,
.el-select .el-input__inner {
  height: 36px; /* 统一输入框高度 */
  border-radius: 6px; /* 边框圆角 */
  background-color: #a8cbff; /* 浅色背景 */
  border-color: #d1d9e6; /* 边框颜色更浅 */
  padding: 0 10px;
}

/* 输入框、选择框和单选框的悬停效果 */
::v-deep .el-input__inner:hover,
.el-select:hover,
.el-radio:hover {
  border-color: #3a7fda; /* 悬停时边框加深 */
  background-color: #eaf2fd; /* 背景色变浅 */
}

/* 表单标签样式美化 */
::v-deep .el-form-item__label {
  color: #34495e; /* 统一字体颜色 */
  font-weight: 600; /* 字体加粗 */
  font-size: 14px; /* 合适的字体大小 */
}
/* 调整单选框的大小 */
.el-radio__label {
  font-size: 13px !important; /* 单选框标签字体大小调整 */
}

</style>